﻿using Ninject;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Test.Common.Log;
using Test.DataAccess.POCO;
using Test.IServices;
using Test.Utility.Extensions;

namespace Test.Services
{
    public class ConfigurationService : BaseService<Configuration>, IConfigurationService
    {
        [Inject]
        public ILogger Logger { get; set; }
        /// <summary>
        /// 获取配置信息，数据库中的同名配置，将覆盖AppSetting的
        /// </summary>
        public string GetByKey(string key)
        {
            string result = string.Empty;

            try
            {
                var confs = GetCacheConfiguration();
                //获取并缓存所有配置
                var conf = confs.FirstOrDefault(c => c.Key == key);
                result = conf.Value ?? result;
            }
            catch (Exception ex)
            {
                Logger.LogException(ex);
            }
            return result;
        }

        public T GetByKey<T>(string key)
        {
            try
            {
                var conf = GetCacheConfiguration().FirstOrDefault(c => c.Key == key);
                return conf.Value.ToObject<T>();
            }
            catch
            {
                return default(T);
            }
        }

        /// <summary>
        /// 获取数据，并缓存全表
        /// </summary>
        /// <param name="refresh">强制刷新缓存</param>
        /// <returns>全表数据</returns>
        public Dictionary<string, string> GetCacheConfiguration(bool refresh = false)
        {
            string key = "AllSiteConfiguration";

            return SiteCache.Get(key, () =>
            {
                var result = Entities.ToDictionary(c => c.Key, c => c.ValueOrJson);//获取数据库中的配置
                foreach (var k in System.Configuration.ConfigurationManager.AppSettings.AllKeys)
                {
                    if (result.ContainsKey(k))
                    {
                        continue;
                    }
                    else
                    {
                        result.Add(k, System.Configuration.ConfigurationManager.AppSettings[k]);
                    }
                }
                return result;
            }, new TimeSpan(24, 0, 0), refresh: refresh);
        }
    }
}
